import React, {useState, useEffect} from 'react';
import {Form, Button, Drawer, Input, Select, Spin, Radio} from 'antd';
import {connect} from 'dva';
import SelectCron from "@/pages/common/cron/SelectCron";

const {Option} = Select;


/**
 * 新增定时任务
 *
 * @author zhangby
 * @date 28/2/20 10:20 am
 */
function CronEdit(props, ref) {
  const [visible, setVisible] = useState(false);
  const [cron, setCron] = useState('* * * * * ?');
  const [oldCron, setOldCron] = useState('* * * * * ?');
  const [cronIsEq, setCronIsEq] = useState(true);
  const {cronId, dispatch, cronSelectData, loading} = props;
  const {getFieldDecorator, resetFields, setFieldsValue} = props.form;

  // 初始化页面
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cron/getCronSelectData',
      });
    }
  }, [])

  // 初始化
  const initEdit = () => {
    resetFields();
    if (dispatch) {
      dispatch({
        type: 'cron/getCronById',
        params: {id: cronId}
      }).then(res => {
        const {result} = res;
        setFieldsValue({
          name: result.name,
          mark: result.mark,
          remarks: result.remarks,
          status: result.status,
        });
        setCron(result.cron);
        setOldCron(result.tails.oldCron);
        setCronIsEq(result.tails.cronIsEq);
      })
      setVisible(true);
    }
  }

  // 提交
  const onsubmit = () => {
    props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-empty
      if (!err) {
        values['cron'] = cron;
        values['id'] = cronId;
        if (dispatch) {
          dispatch({
            type: 'cron/updateCron',
            params: values
          }).then(res => {
            if (res) {
              setVisible(false)
            }
          })
        }
      }
    });
  }

  const formItemLayout = {
    labelCol: {
      xs: {span: 24},
      sm: {span: 7},
    },
    wrapperCol: {
      xs: {span: 24},
      sm: {span: 12},
    },
  };

  return (
    <span>
      <span onClick={initEdit} style={{cursor: 'pointer'}}>
        {
          props.children !== undefined ? props.children
            :
            <Button type="primary" shape="circle" icon="edit"/>
        }
      </span>
      <Drawer
        title="新建定时任务"
        placement="right"
        closable={false}
        onClose={() => setVisible(false)}
        visible={visible}
        width={650}
      >
        <Spin spinning={loading}>
          <Form {...formItemLayout}>
            <Form.Item label="标识">
              {getFieldDecorator('mark', {
                rules: [
                  {
                    required: true,
                    message: '请选择标识',
                  },
                ],
              })(
                <Select placeholder="选择定时任务" showSearch allowClear>
                  {
                    cronSelectData.map((item, key) => (
                      <Option value={item.value} key={key}>{`${item.value} （ ${item.label} ）`}</Option>
                    ))
                  }
                </Select>
              )}
            </Form.Item>
            <Form.Item label="名称">
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                  },
                ],
              })(<Input/>)}
            </Form.Item>
            <Form.Item label="Cron 表达式">
              <SelectCron value={cron} render={val => setCron(val)}/>
              {
                !cronIsEq?
                  <div style={{ fontSize: 12, color: '#c41d7f'}}>
                    <span>初始CRON：</span>
                    <span>{oldCron}</span>
                  </div>
                : null
              }
            </Form.Item>
            <Form.Item label="备注信息">
              {getFieldDecorator('remarks', {})(<Input.TextArea placeholder="备注信息" rows={4}/>)}
            </Form.Item>
            <Form.Item label="状态">
              {getFieldDecorator('status', {})(
                <Radio.Group>
                  <Radio value={'0'}>正常</Radio>
                  <Radio value={'1'}>停用</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Form>
        </Spin>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={() => setVisible(false)} style={{marginRight: 8}}>
            Cancel
          </Button>
          <Button onClick={onsubmit} type="primary">
            Submit
          </Button>
        </div>
      </Drawer>
    </span>
  )
}

const form = Form.create({name: 'CronEdit',})(CronEdit)

export default connect(({cron, loading}) => ({
  loading: loading.models.cron,
  cronSelectData: cron.cronSelectData,
}))(form);
